
public class CircularBuffer implements Buffer<Integer> {
    private Integer[] buffer;
    private int read;
    private int write;
    //------------------------------------------------------------------------------
    public CircularBuffer(int capacity) {
        buffer = new Integer[capacity];
        read = 0;
        write = -1;
    }
    //------------------------------------------------------------------------------
    @Override
    public synchronized void put(Integer item) {
        while (isFull()) {
            try {
                wait();
            } catch (InterruptedException ex) {
                System.out.println("Interrupted exception "
                        + Thread.currentThread() + " while putting " + item);
                return;
            }
        }
        int pos = (write + 1) % buffer.length;
        buffer[pos] = item;
        write = pos;
        System.out.println(item + " added to buffer");
        notifyAll();
    }
    //----------------------------------------------------------------------------
    @Override
    public Integer get() {
        while (isEmpty()) {
            try {
                wait();
            } catch (InterruptedException ex) {
                System.out.println("Interrupted exception in thread " + Thread.currentThread());
                return null;
            }
        }
        Integer item = buffer[read];
        buffer[read] = null;
        read = (1 + read) % buffer.length;
        notifyAll();
        return item;
    }
    //----------------------------------------------------------------------------
    @Override
    public boolean isEmpty() {
        for (int i = 0; i < buffer.length; ++i) {
            if (buffer[i] != null) {
                return false;
            }
        }
        return true;
    }
    //----------------------------------------------------------------------------
    @Override
    public boolean isFull() {
        for (int i = 0; i < buffer.length; ++i) {
            if (buffer[i] == null) {
                return false;
            }
        }
        return true;
    }
    //----------------------------------------------------------------------------
    private void displayBuffer() {
        for (int i = 0; i < buffer.length; ++i) {
            System.out.print(buffer[i] + " ");
        }
        System.out.println();
    }
    //----------------------------------------------------------------------------
}//End class CircularBuffer
